﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Clmp.Data.DBEntity
{
    /// <summary>
    /// 数据库、实体映射管理
    /// </summary>
    class Mapping : IMapping
    {
        private static readonly Dictionary<string, string> PrimaryKeyDictionary = new Dictionary<string, string>();
        private static readonly Dictionary<string, string> TableDictionary = new Dictionary<string, string>();
        #region IMapping 成员
        /// <summary>
        /// 获取数据表的主键列名
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <returns>主键列名</returns>
        public string GetTablePrimaryKey<TEntity>() where TEntity : Entity
        {
            Type entityType = typeof(TEntity);
            string entityName = entityType.Name;
            if (PrimaryKeyDictionary.ContainsKey(entityName))
            {
                return PrimaryKeyDictionary[entityName];
            }
            var props = entityType.GetProperties();
            bool hasID = false;
            foreach(var p in props)
            {
                ColumnAttribute columnInfo;
                object columnInfoObj = p.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault();
                if (columnInfoObj != null)
                {
                    columnInfo = (ColumnAttribute)columnInfoObj;
                    if (columnInfo.IsPrimaryKey)
                    {
                        PrimaryKeyDictionary[entityName] = columnInfo.Name;
                        return columnInfo.Name;
                    }
                }
                if (!hasID)
                {
                    hasID = p.Name == "ID";
                }
            }
            if (hasID)
            {
                PrimaryKeyDictionary[entityName] = "ID";
                return "ID";
            }
            throw new DataContainerException("执行的操作必须指定实体的主键。");
        }
        /// <summary>
        /// 获取实体对应的表名
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <returns>实体对应表名</returns>
        public string GetTableName<TEntity>() where TEntity : Entity
        {
            Type entityType = typeof(TEntity);
            string entityName = entityType.Name;

            if (TableDictionary.ContainsKey(entityName))
            {
                return TableDictionary[entityName];
            }
            TableAttribute tableInfo;
            var tableInfoObj = entityType.GetCustomAttributes(typeof(TableAttribute), false).FirstOrDefault();
            if (tableInfoObj != null)
            {
                tableInfo = (TableAttribute)tableInfoObj;
                TableDictionary[entityName] = tableInfo.Name;
                return tableInfo.Name;
            }
            return entityName;
        }

        #endregion
    }
}
